package io.gitee.twoke.generator.engine.impl;

import io.gitee.twoke.generator.engine.*;
import io.gitee.twoke.generator.engine.impl.*;
import io.gitee.twoke.generator.engine.impl.cfg.GenerateEngineConfigurationImpl;
import io.gitee.twoke.generator.engine.impl.generate.impl.GenerateServiceImpl;
import io.gitee.twoke.generator.engine.impl.generate.method.GlobalMethodManager;
import io.gitee.twoke.generator.engine.impl.generate.parameter.ParameterLoaderManager;
import io.gitee.twoke.generator.engine.impl.interceptor.CommandExecutor;
import io.gitee.twoke.generator.engine.impl.interceptor.SessionFactory;
import io.gitee.twoke.generator.engine.impl.template.impl.TemplateServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class GenerateEngineImpl implements GenerateEngine {

    private String name;
    protected GenerateEngineConfigurationImpl generateEngineConfiguration;
    protected CommandExecutor commandExecutor;
    protected Map<Class<?>, SessionFactory> sessionFactories;

    public GenerateEngineImpl(GenerateEngineConfigurationImpl processEngineConfiguration) {
        this.generateEngineConfiguration = processEngineConfiguration;
        this.name = generateEngineConfiguration.getGenerateEngineName();
        this.commandExecutor = processEngineConfiguration.getCommandExecutor();
        this.sessionFactories = processEngineConfiguration.getSessionFactories();

        if (processEngineConfiguration.isUsingRelationalDatabase() && processEngineConfiguration.getDatabaseSchemaUpdate() != null) {
            commandExecutor.execute(processEngineConfiguration.getSchemaCommandConfig(), new SchemaOperationsGenerateEngineBuild());
        }

        GenerateEngines.registerGenerateEngine(this);

        if (name == null) {
            log.info("default activiti GenerateEngine created");
        } else {
            log.info("GenerateEngine {} created", name);
        }
    }

    public void close() {
        GenerateEngines.unregister(this);
        commandExecutor.execute(generateEngineConfiguration.getSchemaCommandConfig(),
                new SchemaOperationsGenerateEngineClose());
    }

    @Override
    public MetaDataService getMetaDataService() {
        return new MetaTableServiceImpl(this.generateEngineConfiguration);
    }

    @Override
    public TemplateService getTemplateService() {
        return new TemplateServiceImpl(this.generateEngineConfiguration);
    }

    @Override
    public GenerateService getGenerateService() {
        return new GenerateServiceImpl(this.generateEngineConfiguration);
    }

    @Override
    public GlobalMethodManager getGlobalMethodManager() {
        return generateEngineConfiguration.getGlobalMethodManager();
    }

    @Override
    public ParameterLoaderManager getParameterLoaderManager() {
        return generateEngineConfiguration.getParameterLoaderManager();
    }

    @Override
    public String getName() {
        return name;
    }

}
